<template>
  <div class="reply-log">
    <div :ref="chatBoxRef" class="chat-box">
      <div v-for="chatItem of chatLogs" :key="chatItem.id">
        <div v-if="chatItem.isTime" class="divider-time">
          {{ chatItem.content }}
        </div>
        <template v-else>
          <div
            :class="[
              'chat-item',
              {
                'mine-chat': chatItem.isNowUser
              }
            ]"
          >
            <!-- <el-avatar :size="38" :src="avatar" /> -->
            <div class="name-to-avatar">
              {{ chatItem.userName[0] }}
            </div>
            <div class="name">
              <!-- {{ `${chatItem.userName}(${chatItem.userAlias})` }} -->
              {{ chatItem.userName }}
            </div>
            <div class="content">
              <template v-if="Number(chatItem.messageType) === 1">
                <el-image
                  style="max-width: 300px"
                  :src="chatItem.src"
                  :preview-src-list="[chatItem.src]"
                />
              </template>
              <template v-else-if="Number(chatItem.messageType) === 2">
                <el-button @click="onDownload(chatItem.fileId)">
                  <svg-icon icon-class="accessory" />
                  {{ chatItem.replyContent }}
                </el-button>
              </template>
              <template v-else-if="Number(chatItem.messageType) === 3">
                <r-video :width="300" url="/example/食屎啦.mp4" />
              </template>
              <div v-else class="text">
                <TextContent :content="chatItem.replyContent" />
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
    <div v-if="!isClosed" class="send-box">
      <div class="send-content">
        <ChatEdit v-model="textContent" @ctrlEnter="sendText" />
      </div>
      <div class="send-operate">
        <ChatUpload @onUpload="sendFileList" />
        <el-tooltip
          v-model="showTip"
          effect="light"
          :content="$t('workOrderMg.notBlank')"
          placement="top-end"
          :manual="true"
        >
          <el-button type="primary" @click="sendText">{{
            $t('btns.send')
          }}</el-button>
        </el-tooltip>
      </div>
    </div>
  </div>
</template>

<script>
import RVideo from '@/components/r-video'
import ChatEdit from '@/components/r-chat-edit'
import TextContent, {
  getEditContent
} from '@/components/r-chat-edit/TextContent'
import { sendChat, getChatLogs } from '@/api/workOrder'
import {
  uploadBase64File,
  getImgUrl,
  uploadConfig,
  downloadFileByUrl
} from '@/api/file'
import ChatUpload from '@/components/r-upload/chat-upload'
import { getExtension } from '@/utils'

export default {
  components: {
    RVideo,
    ChatEdit,
    TextContent,
    ChatUpload
  },
  inject: ['workOrderId'],
  props: {
    isClosed: {
      default: true,
      type: Boolean
    }
  },
  data() {
    return {
      chatBoxRef: 'chatBoxRef',
      textContent: [],
      showTip: false,
      chatLogs: [],
      fileConfig: uploadConfig(),
      timeInterval: null
    }
  },
  computed: {
    chatBoxDom() {
      return this.$refs[this.chatBoxRef]
    }
  },
  mounted() {
    this.loadData()
    if (this.timeInterval) {
      clearInterval(this.timeInterval)
    }
    this.timeInterval = setInterval(() => {
      this.loadData()
    }, 30 * 1000)
  },
  beforeDestroy() {
    if (this.timeInterval) {
      clearInterval(this.timeInterval)
    }
  },
  methods: {
    async loadData() {
      const { retData } = await getChatLogs({
        workOrderId: this.workOrderId,
        size: 100,
        current: 1
      })
      const { records } = retData || {}
      if (records) {
        records.reverse()
        this.chatLogs = records.map(item => {
          const { messageType } = item
          if (Number(messageType) === 1) {
            item.src = getImgUrl(item.fileId)
          }

          return item
        })
        this.$nextTick(() => {
          this.chatBoxDom.scrollTop = this.chatBoxDom.scrollHeight
        })
      }
    },

    sendText() {
      const content = this.textContent

      const contentArr = getEditContent(content) || []
      if (!contentArr || !contentArr.length) {
        this.showTip = true
        setTimeout(() => {
          this.showTip = false
        }, 1000)
        return
      }
      this.sendTextList(contentArr)
      this.textContent = []
    },
    async sendTextList(textArr) {
      for (const item of textArr) {
        const { type, content } = item
        if (type === 'img') {
          const { retData } = await uploadBase64File(content)
          const { id } = retData || {}
          await sendChat({
            workOrderId: this.workOrderId,
            messageType: 1, // 消息类型 0纯文本 1图片 2文件 3视频
            fileId: id
          })
        } else {
          await sendChat({
            workOrderId: this.workOrderId,
            messageType: 0, // 消息类型 0纯文本 1图片 2文件 3视频
            replyContent: content
          })
        }
        this.loadData()
      }
    },
    async sendFileList(fileList) {
      for (const item of fileList) {
        const { id, originalName } = item || {}
        const extension = getExtension(originalName)
        let messageType = 2
        if (this.fileConfig.imgType.indexOf(extension) !== -1) {
          messageType = 1
        }
        await sendChat({
          workOrderId: this.workOrderId,
          messageType, // 消息类型 0纯文本 1图片 2文件 3视频
          fileId: id,
          replyContent: originalName
        })
      }
      this.loadData()
    },
    onDownload(id) {
      downloadFileByUrl(id)
    }
  }
}
</script>

<style lang="scss" scoped>
@import './style.scss';

.reply-log {
  background: $grayBgColor; // 灰色
  font-size: 14px;

  .send-box {
    padding: 15px 15px;
    border-top: 1px solid #ddd;
    .send-content {
      padding-bottom: 10px;
      height: 120px;
    }
    .send-operate {
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
